/**
 * @description 配置数据角色
 * @author 李艳
 */

import React, {Component} from 'react'
import connect from "react-redux/es/connect/connect";
import {show, hide} from '../../../configs/SharedReducer'
import TransferTable from "../../../commons/components/TransferTable";
import {listAllCanAssignDataRolesByRoleGroupAndUser} from "../EnterpriseUser/EnterpriseUserService";
import {tenantAppModulesConfig} from "../../../configs/CommonComponentsConfig";
import SearchTable from "../../../commons/components/SearchTable";
import {searchListByKeyWithTag} from "../../../commons/utils/CommonUtils";
import {
  insertRelationsByParam,
  listAllAssignedAuthDatas, listAllAssignedAuthTreeDatas, listAllUnAssignedAuthDatas, listAllUnAssignedAuthTreeDatas,
  listDataAuthorizeTypeByAppModuleAndDataRole,
  listDataAuthorizeTypeByDataRole, removeRelationsByParam
} from "./DataRoleManagerService";
import {Row, Input, Col} from 'antd';
import SimpleTable from "../../../commons/components/SimpleTable";
import DetailCard from "../../../commons/components/DetailCard";
import {rowGutter} from "../../../configs/DefaultConfig";

class ConfigDataRole extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataAuthorizeTypeSearchValue: "",
      dataAuthorizeType: [],
      selectedDataAuthType: [],
    }
  }

  componentWillMount() {
    const {roleId} = this.props;
    this.getDataAuthorizeType({roleId});
  }

  onRef = (ref) => {
    this.transferRef = ref;
  };
  handleLeftClick = async (rows) => {
    let ids = [];
    const {roleId} = this.props;
    const {selectedDataAuthType} = this.state;
    for (let i = 0; i < rows.length; i++) {
      ids.push(rows[i].id);
    }
    await removeRelationsByParam({
      dataRoleId: roleId,
      entityIds: ids,
      dataAuthorizeTypeId: selectedDataAuthType[0] ? selectedDataAuthType[0].id : ""
    }).then((data) => {
    }).catch(err => {
      this.props.hide()
    })
  }

  handleRightClick = async (rows) => {
    let ids = [];
    const {roleId} = this.props;
    const {selectedDataAuthType} = this.state;
    for (let i = 0; i < rows.length; i++) {
      ids.push(rows[i].id);
    }
    await insertRelationsByParam({
      dataRoleId: roleId,
      entityIds: ids,
      dataAuthorizeTypeId: selectedDataAuthType[0] ? selectedDataAuthType[0].id : ""
    }).then((data) => {

    }).catch(err => {
      this.props.hide()
    })
  };

  leftService = async (params) => {
    let result = [];
    if (!params || !params.authTypeId) {
      params = {
        roleId: this.props.roleId,
        authTypeId: this.state.selectedDataAuthType[0] ? this.state.selectedDataAuthType[0].id : ""
      };
    }
    await listAllUnAssignedAuthDatas(params).then((res) => {
      result = res;
    });
    return result;

  };

  rightService = async (params) => {
    let result = [];
    if (!params || !params.authTypeId) {
      params = {
        roleId: this.props.roleId,
        authTypeId: this.state.selectedDataAuthType[0] ? this.state.selectedDataAuthType[0].id : ""
      };
    }
    await listAllAssignedAuthDatas(params).then((res) => {
      result = res
    });
    return result;

  };
  leftTreeService = async (params) => {
    let result = [];
    if (!params || !params.authTypeId) {
      params = {
        roleId: this.props.roleId,
        authTypeId: this.state.selectedDataAuthType[0] ? this.state.selectedDataAuthType[0].id : ""
      };
    }
    await listAllUnAssignedAuthTreeDatas(params).then((res) => {
      result = res;
    });
    return result;

  };

  rightTreeService = async (params) => {
    let result = [];
    if (!params || !params.authTypeId) {
      params = {
        roleId: this.props.roleId,
        authTypeId: this.state.selectedDataAuthType[0] ? this.state.selectedDataAuthType[0].id : ""
      };
    }
    await listAllAssignedAuthTreeDatas(params).then((res) => {
      result = res
    });
    return result;

  };

  async JointQueryService(key) {
    let result = [];
    const {userId} = this.props;
    let params = {};
    params.dataRoleGroupId = key;
    params.userId = userId;
    await listAllCanAssignDataRolesByRoleGroupAndUser(params).then((res) => {
      result = res
    });
    return result;

  };

  handleSearch = (value) => {
    this.setState({dataAuthorizeTypeSearchValue: value});
    if (value !== "") {
      searchListByKeyWithTag(this.state.dataAuthorizeType, {keyword: value}, ["code", "name"]).then(res => {
        this.setState({dataAuthorizeType: res})
      })
    }
  };
  getDataAuthorizeType = (param) => {
    this.props.show();
    listDataAuthorizeTypeByDataRole(param).then((res) => {
      this.setState({dataAuthorizeType: res})
    }).catch(err => {
    }).finally(() => {
      this.props.hide();
    })
  };
  appModuleChange = (selected) => {
    const {roleId} = this.props;
    this.transferRef.resetData();
    if (selected && selected.id) {
      let params = {appModuleId: selected.id, roleId: roleId};
      this.props.show();
      listDataAuthorizeTypeByAppModuleAndDataRole(params).then(res => {
        this.setState({dataAuthorizeType: res})
      }).catch(err => {
      })
        .finally(() => {
          this.props.hide();
        })
    } else {//如果点击小叉叉
      this.getDataAuthorizeType({roleId});
    }

  };
  onDataAuthorizeTypeSelected = (selectedRow) => {
    if (selectedRow[0]) {
      this.transferRef.resetData();
      this.setState({selectedDataAuthType: selectedRow})
      if (this.transferRef && selectedRow[0]) {
        let params = {roleId: this.props.roleId, authTypeId: selectedRow[0].id};
        if (selectedRow[0].beTree) {
          this.setState({beTree:true})
          this.transferRef.loadLeftData(params, {}, true);
          this.transferRef.loadRightData(params, {}, true);
        } else {
          this.setState({beTree:false})
          this.transferRef.loadLeftData(params, {}, false);
          this.transferRef.loadRightData(params, {}, false);
        }
      }
    }

  };

  render() {
    const {beTree} = this.state;
    const columns = [
      {
        title: '代码',
        dataIndex: 'code',
        width: 180,
        render(text) {
          return <div className={"text-short-nowidth"} title={text}>{text}</div>
        }
      },
      {
        title: '名称',
        dataIndex: 'name',
        width: 180,
        render(text) {
          return <div className={"text-short-nowidth"} title={text}>{text}</div>
        }
      }
    ];
    return (
      <Row gutter={rowGutter} style={{height: "100%"}}>
        <Col span={8} style={{height: "100%"}}>
          <DetailCard title="数据权限类型"  style={{height: "100%"}}>
            <div className={'tbar-box'}>
              <div className={'tbar-btn-box'}>
                            <span>应用模块：<SearchTable
                              config={tenantAppModulesConfig}
                              selectChange={this.appModuleChange}
                              isNotFormItem={true}
                              initValue={false}
                              style={{width: 100}}/></span>
              </div>
              <div className={'tbar-search-box'}>
                <Input.Search
                  placeholder="请输入代码或名称查询"
                  onSearch={value => this.handleSearch(value)}
                  style={{width: 200}}
                  allowClear
                />
              </div>
            </div>

            <SimpleTable
              data={this.state.dataAuthorizeTypeSearchValue ? this.state.dataAuthorizeType.filter(item => item.tag) : this.state.dataAuthorizeType}
              loading={this.state.leftLoading}
              columns={columns}
              onSelectRow={this.onDataAuthorizeTypeSelected}
            />
          </DetailCard>
        </Col>
        <Col span={16}  style={{height: "100%"}}>
            <TransferTable
              className={"child-card"}
              style={{margin:8,height:"calc(100% - 16px)"}}
              initValue={false}
              handleLeftClick={this.handleLeftClick}
              handleRightClick={this.handleRightClick}
              rightService={this.rightService.bind(this)}
              leftService={this.leftService.bind(this)}
              leftTreeService={this.leftTreeService.bind(this)}
              rightTreeService={this.rightTreeService.bind(this)}
              JointQueryService={this.JointQueryService.bind(this)}
              leftTitle={beTree?"所有":"未分配"}
              leftColumns={columns}
              rightColumns={columns}
              onRef={this.onRef}
            />
        </Col>
      </Row>


    );
  }


}

const mapStateToProps = (state) => {
  return {};
}

const mapDispatchToProps = (dispatch) => {
  return {
    show: () => {
      dispatch(show())
    },
    hide: () => {
      dispatch(hide())
    }
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(ConfigDataRole)


